package cn.hnh.utils;

import cn.hnh.exception.IllegalTokenException;
import cn.hnh.pojo.User;
import cn.hnh.vo.UserVo;
import com.alibaba.fastjson.JSONArray;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    private static final long EXpire_Time=24*60*60*1000;
    private static final String key="CanonU-87";

    /**
     * 生成token
     * @param user
     * @return
     */
    public  String getToken(User user){
        Map<String, Object> map = new HashMap<>();
        return JWT.create()
                .withIssuedAt(new Date())   //生成token时间
                .withExpiresAt(new Date(System.currentTimeMillis()+EXpire_Time))   //过期时间
                .withClaim("userid",user.getId())
                .withClaim("userName",user.getUsername())
                .sign(Algorithm.HMAC256(key));    //使用的加密算法及解密key
    }

    /**
     * 校验token合法性
     * @param token
     * @return
     */
    public  Map<String, Claim> verifyToken(String token) throws IllegalTokenException{
        DecodedJWT jwt = null;
        Map<String, Claim> claims=null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
            jwt = verifier.verify(token);
            claims = jwt.getClaims();
        } catch (Exception e) {
            // e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
            throw new IllegalTokenException(e.getMessage());
        }
        return claims;
    }

    public  String getUserName(String token) throws IllegalTokenException{
        Map<String, Claim> map = verifyToken(token);
        Claim userinfo = map.get("userName");
        return userinfo.asString();
    }

    public  Integer getUserId(String token) throws IllegalTokenException{
        Map<String, Claim> map = verifyToken(token);
        Claim userinfo = map.get("userid");
        return userinfo.asInt();
    }

}
